<template>
  <div>
    <div class="goods">
      <div class="menu-wrapper" ref="menuWrapper">
        <ul>
          <li v-for="(item,index) in goods" class="menu-item" :class="{'current':currentIndex===index}" :key="index"
              @click="selectMenu(index,$event)" ref="menuList">
          <span class="text border-1px">
            <span v-show="item.type>0" class="icon" :class="classMap[item.type]"></span>{{item.name}}
          </span>
          </li>
        </ul>
      </div>
      <div class="foods-wrapper" ref="foodsWrapper">
        <ul>
          <li v-for="(item,index) in goods" class="food-list" ref="foodList" :key="index">
            <h1 class="title">{{item.name}}</h1>
            <ul>
              <li @click="selectFood(food,$event)" v-for="food in item.foods" :key="food.id" class="food-item border-1px">
                <div class="icon">
                  <img width="57" height="57" :src="food.icon">
                </div>
                <div class="content">
                  <h2 class="name">{{food.name}}</h2>
                  <p class="desc">{{food.description}}</p>
                  <div class="extra">
                    <span class="count">月售{{food.sellCount}}</span><!-- <span>好评率{{food.rating}}%</span> -->
                  </div>
                  <div class="price">
                    <span class="now">￥{{food.price}}</span><span class="old"
                      v-show="food.oldPrice">￥{{food.oldPrice}}</span>
                  </div>
                  <div class="cartcontrol-wrapper">
                    <cartcontrol @add="addFood" :food="food"></cartcontrol>
                  </div>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <neworder v-show="showNewOrder"></neworder>
      <shopcart ref="shopcart" :selectFoods="selectFoods" :deliveryPrice="seller.deliveryPrice"
                :minPrice="seller.minPrice"></shopcart>
    </div>
    <food @add="addFood" :food="selectedFood" ref="food"></food>
  </div>
</template>

<script type="text/ecmascript-6">
  import BScroll from 'better-scroll';
  import shopcart from 'components/shopcart/shopcart';
  import cartcontrol from 'components/cartcontrol/cartcontrol';
  import food from 'components/food/food';
  import neworder from 'components/order/neworder';
  import { getCookie } from 'common/js/util';
  var config = require('../../../config');
  config = process.env.NODE_ENV === 'development' ? config.dev : config.build;

  const ERR_OK = 0;
  const debug = process.env.NODE_ENV !== 'production';
  const heartCheck = {
    timeout: 60 * 1000,
    timer: null,
    serverTimer: null,
    reset() {
      this.timer && clearTimeout(this.timer);
      this.serverTimer && clearTimeout(this.serverTimer);
      // return this;
    },
    start(ws) {
      this.reset();
      this.timer = setTimeout(() => {
        // console.log('发送心跳,后端收到后，返回一个心跳消息')
        // onmessage拿到返回的心跳就说明连接正常
        // ws.send(JSON.stringify({ heart: 1 }));
        ws.send('ping');
        this.serverTimer = setTimeout(() => {
        // 如果超过一定时间还没响应(响应后触发重置)，说明后端断开了
        ws.close();
        }, this.timeout);
      }, this.timeout);
    }
  };
  export default {
    props: {
      seller: {
        type: Object
      }
    },
    data() {
      return {
        goods: [],
        listHeight: [],
        scrollY: 0,
        selectedFood: {},
        cartFoods: [],
        wsUri: config.wsUrl, // 'ws://127.0.0.1:5001/apisell/webSocketBuyer/', // ws wss  127.0.0.1:5001 leiyun.site
        lockReconnect: false, // 连接失败不进行重连
        maxReconnect: 10, // 最大重连次数，若连接失败
        websock: null,
        newOrderShow: false
      };
    },
    watch: {
      // heartNum: 'websocketsend'
      socketChangeCount: 'websocketsend'
    },
    computed: {
      // wsUri() {
      //   return config.wsUrl;
      // },
      socketChangeCount() {
        return this.$store.getters.socketChangeCount;
      },
      currentIndex() {
        for (let i = 0; i < this.listHeight.length; i++) {
          let height1 = this.listHeight[i];
          let height2 = this.listHeight[i + 1];
          if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
            this._followScroll(i);
            return i;
          }
        }
        return 0;
      },
      selectFoods() {
        console.log('==========selectFoods ,hartNum=' + this.socketChangeCount);
        console.log(this.cartFoods);
        let foods = [];
        this.goods.forEach((good) => {
          good.foods.forEach((food) => {
            if (food.count) {
              foods.push(food);
            }
          });
        });
        return foods;
      },
      showNewOrder() {
        if (this.$store.getters.orderId) {
          this.newOrderShow = true;
        }
        return this.newOrderShow;
      }
    },
    created() {
      let exp = new Date();
      exp.setTime(exp.getTime() + 7200 * 1000); // 过期时间120分钟
      // 如果url里有num则获取，没有则给默认桌号， 设置进cookie,
      const num = this.$route.query.num;
      if (typeof num !== 'undefined') {
        // alert('num === undefined')
        document.cookie = 'num=' + num + ';expires=' + exp.toGMTString();
      }
      if (getCookie('num') == null) {
        document.cookie = 'num=Z00;expires=' + exp.toGMTString();
      }
      if (!debug) {
        // 如果url里有openid, 设置进cookie
        const openid = this.$route.query.openid;
        if (typeof openid !== 'undefined') {
            document.cookie = 'openid=' + openid + ';expires=' + exp.toGMTString();
        }
        // 获取openid
        if (getCookie('openid') == null) {
            // console.log(config.openidUrl + '?returnUrl=' + encodeURIComponent(config.sellUrl + '/#/'));
            location.href = config.openidUrl + '?returnUrl=' + encodeURIComponent(config.sellUrl + '/#/');
        }
      } else {
        const openid = this.$route.query.openid;
        if (typeof openid !== 'undefined') {
            document.cookie = 'openid=' + openid + ';expires=' + exp.toGMTString();
        } else {
            document.cookie = 'openid=oqS4U6pDmDCEZsP3MJGrwOT6WSYs;expires=' + exp.toGMTString();
        }
      }
      this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee'];
      this.initData();
    },
    mounted() {
      this.initWebSocket();
    },
    methods: {
      initData() {
        const url = debug ? '/goods' : '/buyer/product/list';
        this.$axios.get(url).then((response) => {
          response = response.data;
          if (response.code === ERR_OK) {
            this.goods = response.data;
            this.$nextTick(() => {
              this._initScroll();
              this._calculateHeight();
            });
          }
        });
      },
      selectMenu(index, event) {
        if (!event._constructed) {
          return;
        }
        let foodList = this.$refs.foodList;
        let el = foodList[index];
        this.foodsScroll.scrollToElement(el, 300);
      },
      selectFood(food, event) {
        if (!event._constructed) {
          return;
        }
        this.selectedFood = food;
        this.$refs.food.show();
      },
      addFood(target) {
        console.log('==========addFood ');
        this._drop(target);
      },
      _drop(target) {
        // 体验优化,异步执行下落动画
        this.$nextTick(() => {
          this.$refs.shopcart.drop(target);
        });
      },
      _initScroll() {
        this.meunScroll = new BScroll(this.$refs.menuWrapper, {
          click: true
        });

        this.foodsScroll = new BScroll(this.$refs.foodsWrapper, {
          click: true,
          probeType: 3
        });

        this.foodsScroll.on('scroll', (pos) => {
          // 判断滑动方向，避免下拉时分类高亮错误（如第一分类商品数量为1时，下拉使得第二分类高亮）
          if (pos.y <= 0) {
            this.scrollY = Math.abs(Math.round(pos.y));
          }
        });
      },
      _calculateHeight() {
        let foodList = this.$refs.foodList;
        let height = 0;
        this.listHeight.push(height);
        for (let i = 0; i < foodList.length; i++) {
          let item = foodList[i];
          height += item.clientHeight;
          this.listHeight.push(height);
        }
      },
      _followScroll(index) {
        let menuList = this.$refs.menuList;
        let el = menuList[index];
        this.meunScroll.scrollToElement(el, 300, 0, -100);
      }, // websocket start 1
      initWebSocket() {
        try {
          console.log('init websocket, ' + this.wsUri);
          if ('WebSocket' in window) {
            // console.log(websock);
            if (this.websock != null) {
              console.log('websock.readyState:' + this.websock.readyState);
              console.log('websock.close:' + this.websock.readyState);
            }
            if (this.websock == null || this.websock.readyState > 1) {
              console.log('[初始化websocket] 。。。');
              // natapp 映射的域名，很难连接
              const wsurl = this.wsUri + getCookie('openid') + '/' + getCookie('num');
              this.websock = new WebSocket(wsurl);
              // alert('与服务器的连接失败，请联系管理员清理缓存');
            }
          } else {
            console.log('您的浏览器不支持websocket');
          }
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onclose = this.websocketclose;
        } catch (e) {
          console.log('[初始化websocket] 异常消息：');
          console.log(e);
        }
      },
      reconnect() {
        console.log('尝试重连', this.maxReconnect);
        if (this.lockReconnect || this.maxReconnect <= 0) {
          return;
        }
        this.lockReconnect = true;
        this.maxReconnect--;
        setTimeout(() => {
          this.initWebSocket();
          this.lockReconnect = false;
        }, 10 * 1000);
      },
      // 建立连接
      websocketonopen() {
        heartCheck.start(this.websock); // 心跳检测重置
        console.log('WebSocket连接成功', new Date().toUTCString());
        // websocketsend(); // 这里不可以发送哈
      },
      websocketonerror(e) {
        console.log('WebSocket连接发生错误', e);
        this.reconnect();
      },
      websocketonmessage(e) {
        // 心跳检测重置
        heartCheck.start(this.websock);  // 拿到任何消息都说明当前连接是正确的
        console.log('收到消息websocket ');
        console.log(e.data);
        if (e.data === 'pong') {
          return;
        }
        if (JSON.parse(e.data) && JSON.parse(e.data).msg === 'orderId') {
          console.log(JSON.parse(e.data).data);
          this.newOrderShow = JSON.parse(e.data).data;
          this.cartFoods = [];
          this.$store.dispatch('setOrderId', this.newOrderShow);
          this.$store.dispatch('setCartList', []);
          this.initData();
          return;
        }
        if (JSON.parse(e.data) && JSON.parse(e.data).msg === 'cart') {
          // messageCallback(JSON.parse(e.data));
          this.cartFoods = JSON.parse(e.data).data;
          console.log('cartFoods=' + this.cartFoods);
          if (this.cartFoods && this.cartFoods.length > 0) { // cartFoods=undefined
            this.goods.forEach((good) => {
              const posGoodIndex = this.goods.indexOf(good);
              good.foods.forEach((food) => {
                const posFoodIndex = this.goods[posGoodIndex].foods.indexOf(food);
                const arr = this.cartFoods.map(function(o) { return o.id; });
                const index = arr.indexOf(String(food.id));
                if (index > -1) {
                  console.log(food.count);
                  const cartFood = this.cartFoods[index];
                  const countNum = cartFood.count;
                  food['count'] = countNum;
                  console.log('修改了this.goods的数量, countNum=' + countNum + ', openid=' + cartFood.openid);
                  // this.goods[posGoodIndex].foods[posFoodIndex].count = food.count; // 这种修改无用
                  this.$set(this.goods[posGoodIndex].foods, posFoodIndex, {...food, count: countNum});
                  this.$set(this.goods[posGoodIndex].foods, posFoodIndex, {...food, openid: cartFood.openid});
                } else {
                  if (food.count > 0) {
                    const countNum = food.count - 1;
                    this.$set(this.goods[posGoodIndex].foods, posFoodIndex, {...food, count: countNum}); // 购物车清空了，原列表需要递减
                  }
                }
              });
            });
            // foods = this.cartFoods;
            // this.cartFoods = [];
            console.log(this.goods);
            this.$store.dispatch('incrementCart'); // 购物车有异步更新，当前没有使用这个做监听
            this.$store.dispatch('setCartList', this.cartFoods); // 这个list需要改为存储到本地Storage，然后再从vuex取本地数据
            window.selectedGoods = JSON.stringify(this.cartFoods);
            console.log('cartFoods赋值给foods后，size=' + this.cartFoods.length + ' , window.selelct=' + window.selectedGoods);
          }
          // this.selectFoods = JSON.parse(e.data);
        }
      },
      websocketclose(e) {
        console.log('WebSocket连接关闭，', new Date().toUTCString());
        if (e && e.code !== 1000) {
          console.log('ws连接异常，非正常关闭');
          setTimeout(() => {
            this.reconnect();
          }, 600);
        }
      },
      /**
       * 发起websocket连接，传输数据
       */
      websocketsend() {
        try {
          heartCheck.reset();
          if (!this.selectFoods) return;
          let agentData = {
              type: 'cart',
              openid: getCookie('openid'),
              numTable: getCookie('num'),
              toMessage: this.selectFoods
          };
          console.log(agentData);
          if (this.websock == null) {
            this.initWebSocket();
            setTimeout(() => {
               console.log('发送websocket ,hartNum=' + this.socketChangeCount);
               this.websock.send(JSON.stringify(agentData));
            }, 500);
          }
          if (this.websock.readyState === this.websock.OPEN) {
            this.websock.send(JSON.stringify(agentData));
          } else if (this.websock.readyState === this.websock.CONNECTING) { // 若是 正在开启状态，则等待300毫秒
              // 很多时候，300毫秒都不足以开启,可能是域名问题--------------------error
              let that = this;// 保存当前对象this
              setTimeout(function () {
                 console.log('发送websocket ,hartNum=' + this.socketChangeCount);
                that.websock.send(JSON.stringify(agentData));
              }, 200);
          } else { // 若未开启 ，则等待500毫秒
              this.initWebSocket();
              let that = this;// 保存当前对象this
              setTimeout(function () {
                 console.log('发送websocket ,hartNum=' + this.socketChangeCount);
                that.websock.send(JSON.stringify(agentData));
              }, 500); // 加延迟是为了尽量让ws连接状态变为OPEN
          }
        } catch (e) {
          alert(e);
        }
      }
    }, // methods end
    components: {
      shopcart,
      cartcontrol,
      food,
      neworder
    },
    destroyed() {
      this.socket.close();
    }
  };
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../common/stylus/mixin.styl"

  .goods
    display: flex
    position: absolute
    top: 174px
    bottom: 46px
    width: 100%
    overflow: hidden
    .menu-wrapper
      flex: 0 0 80px
      width: 80px
      background: #f3f5f7
      .menu-item
        display: table
        height: 54px
        width: 56px
        padding: 0 12px
        line-height: 14px
        &.current
          position: relative
          z-index: 10
          margin-top: -1px
          background: #fff
          font-weight: 700
          .text
            border-none()
        .icon
          display: inline-block
          vertical-align: top
          width: 12px
          height: 12px
          margin-right: 2px
          background-size: 12px 12px
          background-repeat: no-repeat
          &.decrease
            bg-image('decrease_3')
          &.discount
            bg-image('discount_3')
          &.guarantee
            bg-image('guarantee_3')
          &.invoice
            bg-image('invoice_3')
          &.special
            bg-image('special_3')
        .text
          display: table-cell
          width: 56px
          vertical-align: middle
          border-1px(rgba(7, 17, 27, 0.1))
          font-size: 12px
    .foods-wrapper
      flex: 1
      .title
        padding-left: 14px
        height: 26px
        line-height: 26px
        border-left: 2px solid #d9dde1
        font-size: 12px
        color: rgb(147, 153, 159)
        background: #f3f5f7
      .food-item
        display: flex
        margin: 18px
        padding-bottom: 18px
        border-1px(rgba(7, 17, 27, 0.1))
        &:last-child
          border-none()
          margin-bottom: 0
        .icon
          flex: 0 0 57px
          margin-right: 10px
        .content
          flex: 1
          .name
            margin: 2px 0 8px 0
            height: 14px
            line-height: 14px
            font-size: 14px
            color: rgb(7, 17, 27)
          .desc, .extra
            line-height: 10px
            font-size: 10px
            color: rgb(147, 153, 159)
          .desc
            line-height: 12px
            margin-bottom: 8px
          .extra
            .count
              margin-right: 12px
          .price
            font-weight: 700
            line-height: 24px
            .now
              margin-right: 8px
              font-size: 14px
              color: rgb(240, 20, 20)
            .old
              text-decoration: line-through
              font-size: 10px
              color: rgb(147, 153, 159)
          .cartcontrol-wrapper
            position: absolute
            right: 0
            bottom: 12px
</style>
